package com.example.mybatisplus.config;


import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
public class DataSourceSlaveConfig {

    /**
     * 是application-test.yml中的spring.datasource.slave配置生效
     *
     * @return
     */
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")

    public DataSource slaveDataSource() {
        return new HikariDataSource();
    }


    /**
     * 事务管理器，在实例化时注入主库slave
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "slaveTransactionManager")

    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * SqlSessionTemplate具有线程安全性
     *
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "oracleJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        return new JdbcTemplate(dataSource);
    }
}
